package com.ellricky.baselib.util;

import static com.ellricky.baselib.BaseConstant.ORDER_ASC;
import static com.ellricky.baselib.BaseConstant.ORDER_DEFAULT;
import static com.ellricky.baselib.BaseConstant.ORDER_DESC;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatRatingBar;
import androidx.fragment.app.Fragment;

import com.andr.common.util.ActivityUtil;
import com.andr.common.util.EmptyUtil;
import com.andr.common.util.StrUtil;
import com.andr.common.util.ToastUtil;
import com.andr.common.util.ViewUtil;
import com.ellricky.baselib.BaseConstant;
import com.ellricky.baselib.BuildConfig;
import com.ellricky.baselib.R;
import com.ellricky.baselib.cache.LocalCacheUtil;
import com.ellricky.baselib.entity.PersonItemEntity;
import com.ellricky.baselib.entity.student.StudentApplyEntity;
import com.ellricky.baselib.entity.teacher.TcDetailEntity;
import com.ellricky.baselib.http.HttpUtils;
import com.ellricky.baselib.listener.OnClassHourConfirmListener;
import com.ellricky.baselib.ui.PdfViewerActivity;
import com.ellricky.baselib.ui.PdfViewerNewActivity;
import com.ellricky.baselib.ui.cla.ClassManageActivity;
import com.ellricky.baselib.ui.consutant.CtSelectActivity;
import com.ellricky.baselib.ui.order.CustomFragmentProviderActivity;
import com.ellricky.baselib.ui.student.StudentApplyDetailActivity;
import com.ellricky.baselib.ui.student.StudentApplyListActivity;
import com.ellricky.baselib.ui.web.WebUtils;
import com.ellricky.baselib.widget.EditAttendView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class EAppUtil {

    private static long firstTime = 0;
    private static Application mApp;

    private static long lastResumeTime = 0;

    public static boolean repeatResume() {
        long time = System.currentTimeMillis();
        long timeD = time - lastResumeTime;
        if (0L < timeD && timeD < 500L) {
            return true;
        } else {
            lastResumeTime = time;
            return false;
        }
    }


    public static String getApiHost() {
        return BuildConfig.HOST;
    }

    public static String getManagerApiHost() {
        return BuildConfig.MANAGER_HOST;
    }

    public static String getTvApiHost() {
        return BuildConfig.TV_HOST;
    }

    public static String getETvApiHost() {
        return BuildConfig.TV_HOST_ELLRICKY;
    }

    public static void exitApp(Context context) {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000) {
            ToastUtil.show(context, "再按一次退出程序");
            firstTime = secondTime;
        } else {
            ActivityUtil.exitApp();
        }
    }

    public static void initApp(Application app) {
        mApp = app;
        LocalCacheUtil.init(mApp);
        WebUtils.initX5Web(app);
        HttpUtils.getInstance().init(app);
    }

    public static void setUserLevel(AppCompatRatingBar rBar, String userLevel) {
        if (!EmptyUtil.isEmpty(userLevel)) {
            rBar.setRating(Float.valueOf(userLevel));
        } else {
            rBar.setRating(0f);
        }
    }


    /**
     * 根据文件类型跳转查看页面
     *
     * @param activity
     * @param fileUrl
     */
    public static void startFileViewerPage(Activity activity, String fileUrl) {
//        if (isPdf(fileUrl)) {
//            Intent intent = new Intent(activity, PdfViewerActivity.class);
//            intent.putExtra(BaseConstant.KEY_URL, fileUrl);
//            activity.startActivity(intent);
//        } else if (isImage(fileUrl)) {
//            Intent intent = new Intent(activity, ImageGalleryActivity.class);
//            ArrayList<String> urlList = new ArrayList<>();
//            urlList.add(fileUrl);
//            intent.putStringArrayListExtra("urlList", urlList);
//            activity.startActivity(intent);
//        } else {
//            String mimeType = getFileMimeType(fileUrl);
//            if (EmptyUtil.isEmpty(mimeType)) {
//                ToastUtil.show(activity, "附件地址为空");
//            } else {
//                ToastUtil.show(activity, "暂不支持" + getFileMimeType(fileUrl) + "格式文件");
//            }
//
//        }
        if (isPdf(fileUrl)) {
            Intent intent = new Intent(activity, PdfViewerActivity.class);
            intent.putExtra(BaseConstant.KEY_URL, fileUrl);
            activity.startActivity(intent);
        } else {
            jumpWeb(activity, "", fileUrl);
        }
    }


    public static void startFileViewerPageOnDetail(Activity activity, String fileName, String fileUrl) {
        /*if (isPdf(fileName)) {
            Intent intent = new Intent(activity, PdfViewerActivity.class);
            intent.putExtra(BaseConstant.KEY_URL, fileUrl);
            activity.startActivity(intent);
        } else if (isImage(fileName)) {
            Intent intent = new Intent(activity, ImageGalleryActivity.class);
            ArrayList<String> urlList = new ArrayList<>();
            urlList.add(fileUrl);
            intent.putStringArrayListExtra("urlList", urlList);
            activity.startActivity(intent);
        } else {
            String mimeType = getFileMimeType(fileName);
            if (EmptyUtil.isEmpty(mimeType)) {
                ToastUtil.show(activity, "附件地址为空");
            } else {
                ToastUtil.show(activity, "暂不支持查看" + mimeType + "格式文件");
            }

        }*/
        //验证是否获取权限
//        int  per = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
//        if(per != PackageManager.PERMISSION_GRANTED)
//        {
//            String[] PERMISSIONS_STORAGE ={
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                     Manifest.permission.ACCESS_NETWORK_STATE,
//                    Manifest.permission.ACCESS_WIFI_STATE,
//                    Manifest.permission.INTERNET,
//                    Manifest.permission.READ_PHONE_STATE
//            };
//            ActivityCompat.requestPermissions(activity,PERMISSIONS_STORAGE,1);
//        }
        /*HashMap map = new HashMap();
        map.put(TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER, true);
        map.put(TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE, true);
        QbSdk.initTbsSettings(map);*/
        jumpWeb(activity, "", fileUrl);
    }

    private static void jumpWeb(Activity context, String title, String url) {
        Intent intent = new Intent(context, PdfViewerNewActivity.class);
        intent.putExtra("web_title_name", title);
        intent.putExtra("web_url", url);
        context.startActivity(intent);
//        WebUtils.jumpWeb(context,title,url);
    }

    public static boolean isPdf(String fileUrl) {
        String mimeType = getFileMimeType(fileUrl);
        return "pdf".equalsIgnoreCase(mimeType);
    }

    public static boolean isImage(String fileUrl) {
        String mimeType = getFileMimeType(fileUrl);
        return "jpg".equalsIgnoreCase(mimeType) || "png".equalsIgnoreCase(mimeType)
                || "jpeg".equalsIgnoreCase(mimeType);

    }

    public static String getFileMimeType(String fileUrl) {
        if (!EmptyUtil.isEmpty(fileUrl)) {
            int fileLen = fileUrl.length();

            return fileUrl.substring(
                    fileUrl.lastIndexOf(".") + 1, fileLen);
        }

        return "";
    }

    public static void onChosePerson(EditAttendView attendView, boolean showSex, int resultCode, Intent data) {
        if (resultCode == BaseConstant.RESULT_CODE_CHOOSE_PERSON) {
            List<PersonItemEntity> chooseDataList = null;
            if (data != null) {
                Serializable ser = data.getSerializableExtra(BaseConstant.KEY_PERSON_LIST);
                if (ser != null) chooseDataList = (List<PersonItemEntity>) ser;
            }

            if (showSex) attendView.updateDataWithSex(chooseDataList);
            else attendView.updateDataWithoutSex(chooseDataList);
        }
    }

///////////////////////////////////////////////////////////////////////////
// 页面跳转
///////////////////////////////////////////////////////////////////////////

    public static void jumpSelctCt(Activity activity, String backvisitId, String customerId) {
        Intent intent = new Intent(activity, CtSelectActivity.class);
        intent.putExtra("backvisitId", backvisitId);
        intent.putExtra("customerId", customerId);
        jumpForResult(activity, intent);
    }


    public static void jumpStuApplyList(Activity activity) {
        Intent intent = new Intent(activity, StudentApplyListActivity.class);
        jumpForResult(activity, intent);
    }

    public static void jumpStuApplyList(Fragment fragment) {
        Activity activity = fragment.getActivity();
        if (activity != null) {
            Intent intent = new Intent(activity, StudentApplyListActivity.class);
            jumpForResult(fragment, intent);
        }
    }

    public static void jumpStuApplyDetail(Activity activity, StudentApplyEntity entity) {
        Intent intent = new Intent(activity, StudentApplyDetailActivity.class);
        intent.putExtra("stu_list_entity", entity);
        jumpForResult(activity, intent);
    }

    public static void jumpClassManage(Fragment fragment) {
        jumpPageWithNoParam(fragment, ClassManageActivity.class);
    }

    public static void jumpClassManage(Activity activity) {
        jumpPageWithNoParam(activity, ClassManageActivity.class);
    }

///////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////

    public static void jumpPageWithNoParam(Activity activity, Class clz) {
        Intent intent = new Intent(activity, clz);
        jumpForResult(activity, intent);
    }

    public static void jumpPageWithNoParam(Fragment frg, Class clz) {
        Activity activity = frg.getActivity();
        if (activity != null) {
            Intent intent = new Intent(activity, clz);
            jumpForResult(frg, intent);
        }
    }

    public static void jumpPageWithParam(Activity activity, Class clz, Bundle bundle) {
        if (activity != null) {
            Intent intent = new Intent(activity, clz);
            intent.putExtras(bundle);
            jumpForResult(activity, intent);
        }
    }

    public static void jumpPageWithId(Activity activity, Class clz, String id) {
        Intent intent = new Intent(activity, clz);
        intent.putExtra(BaseConstant.KEY_ID, id);
        jumpForResult(activity, intent);
    }

    public static void jumpPageWithId(Fragment frg, Class clz, String id) {
        Activity activity = frg.getActivity();
        if (activity != null) {
            Intent intent = new Intent(activity, clz);
            intent.putExtra(BaseConstant.KEY_ID, id);
            jumpForResult(frg, intent);
        }
    }


    public static void jumpForResult(Activity activity, Intent intent) {
        activity.startActivityForResult(intent, 0);
    }

    public static void jumpForResult(Activity activity, Class clz, int code) {
        Intent intent = new Intent(activity, clz);
        activity.startActivityForResult(intent, code);
    }

    public static void jumpForResult(Fragment frg, Intent intent) {
        frg.startActivityForResult(intent, 0);
    }

    public static void jumpCommonFragment(Context context, int key, Bundle extras) {
        Intent intent = new Intent(context, CustomFragmentProviderActivity.class);
        intent.putExtra("clazz", key);
        if (extras != null) {
            intent.putExtras(extras);
        }
        context.startActivity(intent);
    }

///////////////////////////////////////////////////////////////////////////
// 退出登录
///////////////////////////////////////////////////////////////////////////

    public static void onInvalidToken(final Activity context, String msg) {

        EDialogUtil.showTextDialog(context, "", new OnClassHourConfirmListener() {
            @Override
            public void onConfirm(DialogInterface dialogInterface, String hour) {
                if (context != null) {
                    Intent intent = new Intent("com.ellricky.ui.activity.LoginActivity");
                    intent.putExtra("fromMain", true);
                    context.startActivity(intent);
                    context.finish();
                }
            }
        });
    }


///////////////////////////////////////////////////////////////////////////
// other
///////////////////////////////////////////////////////////////////////////

    public static List<String> getValueList(TcDetailEntity data) {
        List<String> valueList = new ArrayList<>();
        valueList.add(
                StrUtil.filterEmpty(data.getClassNum(), "0")
        );
        valueList.add(
                StrUtil.filterEmpty(data.getClassMonthNumRent(), "0%")
        );
        valueList.add(
                StrUtil.filterEmpty(data.getTempClassNum(), "0")
        );
        valueList.add(
                StrUtil.filterEmpty(data.getVipRent(), "0%")
        );

        valueList.add(
                StrUtil.filterEmpty(data.getVipStudentNum(), "0")
        );
        valueList.add(
                StrUtil.filterEmpty(data.getPriceRent(), "0%")
        );
        valueList.add(
                StrUtil.filterEmpty(data.getToStudentNum(), "0")
        );
        valueList.add(
                StrUtil.filterEmpty(data.getClueNum(), "0%")
        );

        valueList.add(
                StrUtil.filterEmpty(data.getClassMonthNum(), "0")
        );
        valueList.add(
                StrUtil.filterEmpty(data.getClassMonthNumRent(), "0%")
        );
        valueList.add(
                StrUtil.filterEmpty(data.getNewStudentNum(), "0")
        );
        valueList.add(
                StrUtil.filterEmpty(data.getPriceMonthRent(), "0%")
        );

        return valueList;
    }

    public static String getStuOrder(Context context, TextView tv, String order) {
        if (StrUtil.isEquals(ORDER_ASC, order)) {
            order = ORDER_DESC;
            ViewUtil.setTextViewDrawable(context, tv, R.drawable.base_icon_order_desc, 2);
        } else if (StrUtil.isEquals(ORDER_DESC, order)) {
            order = ORDER_DEFAULT;
            ViewUtil.setTextViewDrawable(context, tv, R.drawable.base_icon_order_nor, 2);
        } else {
            order = ORDER_ASC;
            ViewUtil.setTextViewDrawable(context, tv, R.drawable.base_icon_order_asc, 2);
        }
        return order;
    }
}

